package com.online.customerchatserver.thread;


import com.online.customerchatserver.entity.Message;
import com.online.customerchatserver.service.MessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import static java.lang.Thread.sleep;

/**
 * Created by littleheng on 2018/5/2
 */
public class MessageBatchManageThread implements Runnable {

    private MessageService messageService;

    private Logger logger = LoggerFactory.getLogger(getClass());


    @Override
    public void run() {

        this.messageService = SpringApplicationContextHolder.getApplicationContext().getBean(MessageService.class);

        ThreadLock lock = new ThreadLock();

        //  循环等待10s后再次获取锁
        while (true) {
            if (lock.getOprLock()) {

                System.out.println("message获取锁");
                System.out.println(ThreadLock.agentMessagesMap);
                System.out.println(ThreadLock.messagesMap);

                if (ThreadLock.messagesMap.size() > 0 || ThreadLock.agentMessagesMap.size() > 0) {

                    System.out.println("哈哈哈，message开始啦");

                    List<Message> messages = new ArrayList<Message>();

                    Iterator<Map.Entry<String, Message>> entries0 = ThreadLock.messagesMap.entrySet().iterator();
                    Iterator<Map.Entry<String, Message>> entries1 = ThreadLock.agentMessagesMap.entrySet().iterator();

                    while (entries0.hasNext()) {
                        Map.Entry<String, Message> entry = entries0.next();
                        Message message = entry.getValue();
                        messages.add(message);
                        entries0.remove();
                    }

                    while (entries1.hasNext()) {
                        Map.Entry<String, Message> entry = entries1.next();
                        Message message = entry.getValue();
                        messages.add(message);
                        entries1.remove();
                    }
                    lock.unOprLock();

                    messageService.addBatchMessage(messages);
                } else {
                    lock.unOprLock();
                }

                try {
                    sleep(10000);
                } catch (InterruptedException e) {
                    logger.info(e.getMessage(), e);
                }
            }
        }
    }
}